package com.xyy.kingdeejdy.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smecloud.apigw.client.ApigwClient;
import com.smecloud.apigw.constant.HttpMethod;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import com.smecloud.apigw.util.SHAUtil;
import com.xyy.kingdeejdy.pojo.erp.help.ResultPo;
import com.xyy.kingdeejdy.pojo.erp.help.ResultToken;
import com.xyy.kingdeejdy.utils.jdy.JdySecret;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author itmei
 * @Date 2023/7/16 13:20
 * @description: 缓存token
 * @Title: TokenCache
 * @Package com.xyy.jd_clund.utils
 */
@Slf4j
public class TokenCache {

    private static String token;
    private static Long expirationTime;

    public static synchronized String getToken() {
        // 检查Token是否存在且未过期
        long time = DateUtils.getDayEnd().getTime();
        if (token != null && expirationTime < time) {
            return token; // 返回现有的Token
        }
        String newToken = null;
        try {
            // 如果Token不存在或已过期，则重新获取Token
            ApiRequest apiRequest = new ApiRequest(HttpMethod.GET, "api.kingdee.com", "/jdyconnector/app_management/kingdee_auth_token");
            String appKey = JdySecret.get().getAppKey();
            String appSecret = JdySecret.get().getAppSecret();
            Map<String, String> map = new HashMap<>();
            map.put("app_key", appKey);
            String appSignature = SHAUtil.SHA256HMAC(appKey, appSecret);
            appSignature = Base64.getEncoder().encodeToString(appSignature.getBytes());
            map.put("app_signature", appSignature);
            apiRequest.setQuerys(map);
            apiRequest.setBodyJson(JSONObject.toJSONString("").getBytes());
            ApiResult send = ApigwClient.getInstance().send(apiRequest);
            ResultPo resultPo = JSON.parseObject(send.getBody(), ResultPo.class);
            ResultToken data = JSON.parseObject(JSON.toJSONString(resultPo.getData()), ResultToken.class);
            newToken = data.getAccessToken();
            // 假设获取到的新Token为newToken
            token = newToken;
            expirationTime = new Date().getTime(); // 设置Token有效期为一天
            log.info("Token过期重新获取:{} ", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newToken; // 返回新获取的Token
    }
}
